import { getDepartmentList, getDoctorList, getScheduleList } from '@/api/hospital/hospitalList';
import { IDeparmentList, IDoctorList, IScheduleItem, IScheduleList } from '@/api/hospital/model/hospitalListTypes';
import { Button, Card, Col, Pagination, Row, Table, Tag } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import Tree, { DataNode } from 'antd/lib/tree';
import { render } from 'nprogress';
import { stringify } from 'querystring';
import React, { Key, useEffect, useState } from 'react'
import { useParams } from 'react-router-dom';

export default function HospitalSchedule() {
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            width:80,
            align:'center',
            render(value,row,index){
                return  (index + 1)
            }
        },
        {
            title: '职称',
            dataIndex:'title'
        },
        {
            title: '号源时间',
            dataIndex:'workDate'
        },
        {
            title: '总预约数',
            dataIndex:'reservedNumber'
        },
        {
            title: '剩余预约数',
            dataIndex:'availableNumber'
        },
        {
            title: '挂号费(元)',
            dataIndex:'amount'
        },
        {
            title: '擅长技能',
            dataIndex:'skill'
        }
    ]

    // 获取params中的hoscode
    const { hoscode } = useParams()
    // 定义排班相关状态
    let [departmentList, setDepartmentList] = useState<IDeparmentList>([])
    let [depcode, setDepcode] = useState<string>()
    let [scheduleList, setScheduleList] = useState<IScheduleList>([])
    let [hosname, setHosname] = useState<string>()
    let [workDate, setWorkDate] = useState<string>()
    let [doctorList, setDoctorList] = useState<IDoctorList>([])
    let [depname, setDepname] = useState<string>()
    // 定义一级科室 depcode 组成的数组状态
    let [extendedKeys, setExtendedKeys] = useState<string[]>([])
    // 分页相关状态
    let [current, setCurrent] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(5)
    let [total, setTotal] = useState<number>(10)
    // 定义异步方法
    async function _getDepartmentList() {
        let departmentList = await getDepartmentList(hoscode as string)
        console.log(departmentList)
        // 1. 将一级科室不可选中
        departmentList = departmentList.map(department => {
            // interface上增加一个可选属性 disabled
            department.disabled = true
            return department
        })
        // 2. 展开一级节点
        let extendedKeys = departmentList.map(department => department.depcode)
        // console.log('extendedKeys',extendedKeys)
        setExtendedKeys(extendedKeys)
        setDepartmentList(departmentList)

        // 3. 获取默认第一个科室的depcode，并设置状态
        console.log((departmentList[0].children as IDeparmentList)[0].depcode)
        let depcode = (departmentList[0].children as IDeparmentList)[0].depcode
        // 设置科室编码和科室名字
        setDepcode(depcode)
        setDepname((departmentList[0].children as IDeparmentList)[0].depname)
    }
    // 获取排班日期数据
    async function _getScheduleList() {
        // 4. 获取排班日期分页数据
        let { total, bookingScheduleList, baseMap } = await getScheduleList({
            page: current,
            limit: pageSize,
            hoscode: hoscode as string,
            depcode: depcode as string
        })
        // 设置状态
        setScheduleList(bookingScheduleList)
        setTotal(total)
        setHosname(baseMap.hosname)
        // 让排班日期的第一个默认被选中
        console.log('bookingScheduleList', bookingScheduleList)
        bookingScheduleList[0] && setWorkDate(bookingScheduleList[0].workDate)

    }
    /**
     * 获取排班医生数据
     */
    async function _getDoctorList(){
        
        let doctors = await getDoctorList({hoscode:hoscode as string,depcode:depcode as string,workDate:workDate as string})
        setDoctorList(doctors)
        console.log(doctors)
    }
    useEffect(()=>{
       
        workDate && _getDoctorList()
    },[workDate])

    useEffect(()=>{// componentDidMount + componentDidUpdate
        // didMount时， depcode是undefined
        // 重置医生列表和workDate
        setWorkDate('')
        setDoctorList([])
        depcode && _getScheduleList()
    },[depcode, current, pageSize])

    // 页面加载完，调用获取科室列表
    useEffect(() => {
        _getDepartmentList()
    }, [])
    // 根据可视区的高度，计算科室列表div高度
    let height = document.documentElement.clientHeight - 64 - 34 - 90
    return (
        <Card>
            <div className='mb20'>选择：{hosname} / {depname} / {workDate}</div>
            <Row gutter={20}>
                <Col span={5}>
                    <div style={{ height, overflowY: 'scroll' }}>
                        <Tree
                            // onSelect={onSelect}
                            // onCheck={onCheck}
                            fieldNames={{
                                title: 'depname',
                                key: 'depcode'
                            }}
                            selectedKeys={[depcode as string]}
                            expandedKeys={extendedKeys}
                            treeData={departmentList as []}
                            onSelect={(selectedKeys: Key[], info:any)=>{
                                console.log(selectedKeys, info)
                                setDepcode(info.node.depcode)
                                setDepname(info.node.depname)
                            }}
                        />
                    </div>
                </Col>
                <Col span={19}>
                    {scheduleList.map((schedule, index) => (
                        <Tag onClick={()=>{
                            setWorkDate(schedule.workDate)
                        }} key={index} color={workDate === schedule.workDate ? 'green' : ''}>
                            <div>{schedule.workDate} {schedule.dayOfWeek}</div>
                            <div>{schedule.docCount} / {schedule.reservedNumber}</div>
                        </Tag>
                    ))}


                    {/* 分页 */}
                    <Pagination
                        className='mt20 mb20'
                        current={current}
                        pageSize={pageSize}
                        total={total}
                        onChange={async (page: number, pageSize: number) => {
                            setCurrent(page)
                            setPageSize(pageSize)
                        }}
                    />

                    {/* 表格 */}
                    <Table
                        rowKey={'id'}
                        columns={columns}
                        dataSource={doctorList}
                    />

                    <Button className='mt20'>返回</Button>
                </Col>
            </Row>
        </Card>
    )
}
